<template>
    <div class="co-main-page">
        <div class="co-toolbar box-row">
            <div>
                <el-form-item label="元件分类:" size="default">
                    <el-select v-model="query.cat_id" style="width: 120px;">
                        <el-option
                            v-for="item in categorys"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </div>
            <div>
                <el-input size="default" v-model="query.code" placeholder="检索元件/物料编号" @clear="onSearch" clearable></el-input>
            </div>
            <div><el-button size="default" type="primary" @click="onSearch">查找</el-button></div>
            <div style="flex: 1 1 0%; text-align: right;">
                <el-button-group size="default">
                    <el-button type="primary" @click="onCategoryManage">更多设置</el-button>
                    <el-button type="danger" @click="onCreate(null)">添加商品</el-button>
                </el-button-group>
            </div>
        </div>
        <div class="ui-data-list-panel">
            <el-table 
                :data="data" 
                size="small" 
                ref="dragableGoodsTable" 
                :height="sizes?.tbHeight" 
                highlight-current-row
                @cell-mouse-enter="onDragable"
            >
                <el-table-column width="35">
                    <template #default>
                        <el-icon 
                            :size="18"
                            class="goods_table_move_class"
                            style="cursor: pointer;margin-top: 5px;"
                        >
                            <DCaret />
                        </el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="商品名称"></el-table-column>
                <el-table-column label="分类">
                    <template v-slot:default="scope">
                        <span v-category="{v:scope.row.category_ids, tpl:cats}"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="sale_price" label="售价（元）" align="right" width="130" :formatter="rmbFormatter"></el-table-column>
                <el-table-column prop="num" label="货架库存" align="right" width="100"></el-table-column>
                <el-table-column prop="code" label="条码"></el-table-column>
                <el-table-column label="网费支付">
                    <template v-slot:default="scope">
                        <el-switch v-model="scope.row.allow_mb"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                    <template v-slot:default="{row}">
                        <el-button-group size="small">
                            <el-button type="primary" @click="onCreate(row)">编辑</el-button>
                            <el-button type="danger" @click="onRemove(row)">删除</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
            <div class="ui-pagination-ctn">
                <el-pagination :page-size="query.limit" :current-page="query.page" @current-change="onCurrentPageChanged" @size-change="onPageSizeChange" :page-sizes="[23, 50, 100, 200]" layout="sizes, total, prev, pager, next" :total="total"></el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
import { reactive, ref, toRefs, computed } from 'vue';
import { Session, UIMode } from '../uiframe/services/session';
import CreateGoodsDialog from './dialog/CreateGoodsDialog.vue'
import GoodsCategoryDialog from './dialog/GoodsCategoryDialog.vue';
import { UiShowDialog } from '../uiframe/layout/components/CompFactory.vue';
import { socket, useSocket } from '../uiframe/services/socket';
import { DCaret } from '@element-plus/icons-vue';
import Sortable from "sortablejs"
import { ElMessage, ElMessageBox } from 'element-plus';
import directives from '../uiframe/services/directives';
import { dict } from '../uiframe/utils';

export default {
    components:{
        DCaret
    },
    directives,
    setup(props){
        let data = reactive({
            data: [],
            query: {
                code: '', limit: 23, page: 1
            },
            total: 0,
            dragableGoodsTable:null,
            sizes: computed(() => {
                let h = UIMode.mh.value
                return {
                    tbHeight: h - 34 - 48
                }
            }),
            categorys:[],
            cats:{},
        })


        const onSearch = () => {
            useSocket().then(socket=>{
                socket.rpc('components', data.query).then(({success, data:res})=>{
                    if(success){
                        data.data = res.data;
                        data.total = res.total;
                    }
                })
            })
        },
        onmessage = (msg) => { ElMessage({ type: msg.success ? 'success' : 'error', message: msg.message }) },
        formatter = {
            rmbFormatter:(r, c, v) => v ? v.toFixed(2) : '0.00'
        },
        methods = {
            onCurrentPageChanged:(page) => {
                data.query.page = page;
                onSearch();
            },
            onPageSizeChange:(limit) => {
                data.query.limit = limit;
                onSearch();
            },
            onCreate:(payload) => {
                if(!data.categorys.length){
                    onmessage({success:false,message:'中心服务器离线.'})
                    return false
                }
                UiShowDialog(GoodsCategoryDialog, {payload,categorys:data.categorys}).then(res => {
                    onSearch();
                }).catch(res => {})
            },
            onRemove:(row)=>{
                ElMessageBox.confirm('此操作将永久删除该商品, 是否继续?', '提示', {onfirmButtonText: '继续删除',cancelButtonText: '取消',type: 'warning'}).then(() => {
                    useSocket().then(socket=>{
                        socket.rpc('goods.remove', {id:row.id}, 18000).then(res=>{
                            onmessage(res);
                        }).catch(res=>{
                            onmessage(res);
                        })
                    })
                }).catch(() => {})
            },
            onCategoryManage: () => {
                if(!data.categorys.length){
                    onmessage({success:false,message:'中心服务器离线.'})
                    return false
                }
                UiShowDialog(GoodsCategoryDialog, {}).then(res => {
                    onSearch();
                }).catch(res => {})
            },
            onDragable:() => {
                const tbody = data.dragableGoodsTable.$el.querySelector(`tbody`);
                Sortable.create(tbody, {
                    group: {
                        name: "name",
                        pull: true,
                        put: true,
                    },
                    handle: ".goods_table_move_class",
                    easing: 'cubic-bezier(1, 0, 0, 1)',
                    onEnd({oldIndex,newIndex}) {
                        let payload = [data.data[oldIndex].id, data.data[newIndex].id];
                        if (oldIndex !== newIndex) {
                            useSocket().then(socket=>socket.rpc('move_goods', payload).then(res=>{
                                onmessage(res)
                            }).catch(res=>{
                                onmessage(res)
                            }))
                            /*const currRow = data.data.splice(oldIndex, 1)[0];
                            data.data.splice(newIndex, 0, currRow);*/
                        }
                    }
                });
            }
        }
        
        useSocket().then(socket=>{
            socket.rpc('category',{}).then(({success, data:res})=>{
                if(success){
                    data.categorys = res;
                    data.cats = dict(res, 'id', 'name');
                    data.query.cat_id = res[0].id;
                    onSearch();
                }
            })
        })
        return {
            ...toRefs(data),
            ...formatter,
            ...methods,
            onSearch
        }
    }
}
</script>
<style lang="scss">
.co-main-page {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    .el-form-item{ margin-bottom: 0;}
}
</style>